package com.tutorial;

import java.io.StringWriter;

import spark.Request;
import spark.Response;
import spark.Route;
import spark.Spark;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;
import com.mongodb.ServerAddress;

import freemarker.template.Configuration;
import freemarker.template.Template;

public class HelloWorldSparkFreemarkerMongoDBStyle {

	public static void main(String[] args) {
		
		final Configuration config = new Configuration();
		config.setClassForTemplateLoading(HelloWorldSparkFreemarkerMongoDBStyle.class, "/");
		
		Spark.get(new Route("/") {
			
			@Override
			public Object handle(Request request, Response response){
				Template template;
				StringWriter writer = new StringWriter();
				try {
					MongoClient mongoClient = new MongoClient(new ServerAddress("localhost", 27017));
					DB database = mongoClient.getDB("test");
					DBCollection dbCollection = database.getCollection("test");
					template = config.getTemplate("hello.ftl");
					template.process(dbCollection.findOne(), writer);
				} catch (Exception e) {
					halt(500);
					e.printStackTrace();
				}

				return writer;
			}
		});
	}

}
